﻿namespace dotnet_notes.Tools
{
    /// <summary>
    /// 日期时间工具类
    /// </summary>
    public static class DateTimeTool
    {
        /// <summary>
        /// 获取当天的周开始日期
        /// </summary>
        /// <param name="dateTime">指定的日期</param>
        /// <returns></returns>
        public static DateTime GetWeekStartDate(DateTime dateTime)
        {
            return dateTime.DayOfWeek == DayOfWeek.Sunday
                ? dateTime.AddDays(-6)
                : dateTime.AddDays(-((int)dateTime.DayOfWeek - 1));
        }

        /// <summary>
        /// 获取当天上周日期列表
        /// </summary>
        /// <param name="dateTime">指定的日期</param>
        /// <returns></returns>
        public static List<DateTime> GetLastWeekDateList(DateTime dateTime)
        {
            var list = new List<DateTime>();
            var startDate = GetWeekStartDate(dateTime).AddDays(-7);

            for (int i = 0; i < 7; i++)
            {
                list.Add(startDate.AddDays(i));
            }

            return list;
        }

        /// <summary>
        /// 将指定的时间区间按天拆分
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        public static List<DateTimeInterval> SplitTimeIntervalByDays(DateTime startTime, DateTime endTime)
        {
            var list = new List<DateTimeInterval>();
            var currentTime = startTime;

            while (currentTime < endTime)
            {
                // 如果下一天超过了结束时间, 则取结束时间作为右区间的值
                var nextDay = currentTime.Date.AddDays(1);
                var nextTime = nextDay <= endTime.Date ? nextDay : endTime;

                list.Add(new DateTimeInterval
                {
                    Left = currentTime,
                    Right = nextTime
                });

                currentTime = nextTime;
            }

            return list;
        }
    }
}
